﻿
CREATE PROCEDURE [dbo].[CashRegisterDocUpdate]
(--кассовый чек (розничная продажа)
	@DocDate smalldatetime,
	@DocNumber varchar(20),
	@DepartmentUserId int,
	@SaleDiscountTypesId int, --тип скидки
	@СashlessPayment bit,			--признак безналичной оплаты 0-наличная, 1-безналичная
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @orgDocDate smalldatetime, @orgContragentId int, @orgCashRegisterShiftId int
DECLARE @orgDocTypeId int, @orgDepartmentUserId int, @orgSaleDiscountTypesId int

	SET NOCOUNT ON

IF (@DocDate Is Null) OR (@DepartmentUserId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @orgDocTypeId = DocTypeId, @orgDocDate = DocDate, @orgContragentId = ContragentId,
@orgCashRegisterShiftId = CashRegisterShiftId, @orgDepartmentUserId = DepartmentUserId,
@orgSaleDiscountTypesId = ShiftDepartmentId
FROM CA.Documents WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @orgDocTypeId <> 3
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Неправильный тип документа!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @orgDocDate <> @DocDate
BEGIN
	IF NOT EXISTS (
	SELECT TOP (1) Id FROM CD.CashRegisterShifts 
	WHERE Id = @orgCashRegisterShiftId AND OpenDT < @DocDate AND dateadd(hh, 24, OpenDT) > @DocDate
	AND ( CloseDT > @DocDate OR (CloseDT Is Null) ) )
	BEGIN
		SELECT @intErrCode = 4, 
		@strMsg = 'Новая дата не попадает в период кассовой смены!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END

	IF (@orgDocDate < @DocDate)
	BEGIN --проверить возвраты по чеку
		IF EXISTS (SELECT D.Id FROM CA.GoodsDocLines AS R INNER JOIN
               CA.Documents AS D ON R.DocId = D.Id INNER JOIN
               CA.GoodsDocLines AS S ON R.ReturnLineId = S.Id
               WHERE S.DocId = @Original_Id AND D.DocDate < @DocDate)
		BEGIN
			SELECT @intErrCode = 5, 
			@strMsg = 'Новая дата чека больше даты возвратов по чеку!'
			RAISERROR (@strMsg, 11, 1)
			RETURN @intErrCode
		END
	END

END

IF ( IsNull(@SaleDiscountTypesId, -123456) <> IsNull(@orgSaleDiscountTypesId, -123456)) AND (@SaleDiscountTypesId Is Not Null)
BEGIN
	IF NOT EXISTS (SELECT * FROM CO.SaleDiscountTypes WHERE ID = @SaleDiscountTypesId AND ToDelete = 0)
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		SELECT @intErrCode = 6, 
		@strMsg = 'Отсутствует тип скидки с идентификатором ' + cast(@SaleDiscountTypesId as varchar(20)) + ' !'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END
END

IF (@orgSaleDiscountTypesId Is Not Null) AND (@SaleDiscountTypesId Is Null) --раньше скидка была 
BEGIN
	IF EXISTS (SELECT * FROM [CA].[GoodsDocLines] WHERE DocId = @Original_Id AND (DiscountValue Is Not Null) )
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		SELECT @intErrCode = 7, 
		@strMsg = 'Для чека существуют строки со скидкой!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END
END

EXEC @intRet = dbo.CheckAllowUpdateDeleteForRecord @Original_Id
IF @intRet <> 0 RETURN @intRet

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

	SET NOCOUNT OFF;
UPDATE [CA].[Documents] SET 
[DocDate] = @DocDate, 
[DocNumber] = @DocNumber, 
DepartmentUserId = @DepartmentUserId, 
СashlessPayment = @СashlessPayment, 
ShiftDepartmentId = @SaleDiscountTypesId,
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id;
	
SELECT Id, DepartmentId, DocTypeId, DocDate, DocNumber, 
ContragentId, CashRegisterShiftId, DepartmentUserId, 
СashlessPayment, ShiftDepartmentId AS SaleDiscountTypesId,
Note, MD, MW FROM CA.Documents WHERE (Id = @Original_Id)

RETURN 0
